import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';
import { DatePipe } from '@angular/common';
import { Router, ActivatedRoute } from '@angular/router';
import { _HttpClient } from '@delon/theme';
import { environment } from '../../../../environments/environment';

@Component({
    selector: 'app-executiondetail',
    templateUrl: './executionDetail.component.html',
    styleUrls: ['./dispatchList.component.less']
})
export class ExecutionDetailComponent implements OnInit {
    operaData: any = {};
    apiUrl: any = {};
    rowThree = { 'display': 'inline-block', 'width': '150px', 'text-align': 'right' };
    stationSelect: any = [];
    devNameSelect: any = [];
    workTypeSelect: any = [];
    queryParams: any = {};
    infoParams: any = {};
    sfVisible = false;
    sanfangTemp: any = [];
    sanfangList: any = [];
    skywinList: any = [];
    problemList: any = [];
    newproblemList: any = [];
    peopleList: any;
    operaList: any = [
        { addModal: false }
    ];
    devList: any = [];
    finishStatus: any;
    isLoading: any = {};
    readStatus = true;

    constructor(
        private msg: NzMessageService,
        private activatedRoute: ActivatedRoute,
        public ls: LocalStorage,
        private datePipe: DatePipe,
        private router: Router,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        this.activatedRoute.queryParams.subscribe(param => {
            Object.assign(this.queryParams, param);
            if (this.queryParams.vcTeammembername) {
                this.queryParams.vcTeammembername = this.queryParams.vcTeammembername.split(',');
            }
            this.readStatus = this.queryParams.vcStatus === '4' ? false : true;
            // 人员
            this.http.post(environment.devscore + '/orgPerson/queryList', { orgId: this.queryParams.vcOrgId, qualifictionId: '1' }).subscribe((res: any) => {
                if (!res.code) {
                    this.peopleList = res.data;
                }
            });
            if (this.queryParams.vcDevid) {
                for (let i = 0; i < this.queryParams.vcDevid.split(',').length; i++) {
                    this.devList.push({
                        opValue: this.queryParams.vcDevid.split(',')[i],
                        opName: this.queryParams.vcDevname.split(',')[i]
                    });
                }
            }
            switch (this.queryParams.vcFinished) {
                case '已完成':
                    this.queryParams.vcFinished = '0';
                    break;
                case '部分完成':
                    this.queryParams.vcFinished = '1';
                    break;
                case '未完成':
                    this.queryParams.vcFinished = '2';
                    break;
            }
        });
        window.addEventListener('message', (data) => {
            if (data.data && data.data !== 'undefined' && JSON.stringify(data.data).indexOf('webpackOk') === -1) {
                this.sanfangTemp.push(data.data.text);
                this.sanfangList = this.unique(this.sanfangTemp);
            }
        });
        this.http.get(environment.project + '/dayWorkSgrwxkm/query?vcSta=' + this.queryParams.vcStaid + '&dtWorkDay=' + this.queryParams.dtWorkdate).subscribe((res: any) => {
            if (!res.code) {
                this.skywinList = res.meta.list;
            }
        });
        this.finishStatus = 1;
        if (this.queryParams.vcFinished === 0) {
            this.finishStatus = 0;
        }
        this.apiUrl.add = environment.project + '/safeProblem/add';
        this.getSafeProblem();
        this.finish(this.queryParams.vcFinished);
    }
    getSafeProblem() {
        this.http.get(environment.project + '/safeProblem/queryByIds?ids=' + this.queryParams.vcProbids).subscribe((res: any) => {
            if (!res.code) {
                this.problemList = res.data;
                if (this.queryParams.vcDealprobId) {
                    const vcDealProbs = this.queryParams.vcDealprobId.split(',');
                    for (const item of vcDealProbs) {
                        for (const list of this.problemList) {
                            if (item === list.id) {
                                list.checked = true;
                            }
                        }
                    }
                }
            }
        });
        this.http.get(environment.project + '/safeProblem/querySafeProlemBySource?sourceType=1&sourceId=' + this.queryParams.vcId).subscribe((res: any) => {
            if (!res.code) {
                this.newproblemList = res.data;
            }
        });
    }
    finish(e) {
        this.finishStatus = e;
    }
    // 去重
    unique(arr) {
        return Array.from(new Set(arr));
    }
    back() {
        this.router.navigate(['dispatchList/' + this.queryParams.typeName]);
    }
    queEnter() {
        this.modalShow('addModal');
    }
    sanfang() {
        this.sfVisible = true;
    }
    sfOk() {
        this.sfVisible = false;
        this.queryParams.vcRiskinfo = this.sanfangList.toString();
        this.sanfangTemp = [];
    }
    sfCancal() {
        this.sfVisible = false;
    }
    modalShow(type) {
        this.operaList[type] = true;
    }
    modalHide(type) {
        this.operaList[type] = false;
    }
    skywinChange(event) {
        this.skywinList.forEach(data => {
            if (data.nId === event) {
                this.queryParams.vcSkyplanrange = data.vcProject;
                this.queryParams.dtSkywinplantime = data.vcSkywinstime;
                this.queryParams.dtSkywinplanetime = data.vcSkywinetime;
            }
        });
    }
    dateYearMonth(data) {
        if (data instanceof Date) {
            return this.datePipe.transform(data, 'yyyy-MM-dd HH:mm');
        } else {
            return;
        }
    }
    operaButton(type) {
        this.isLoading[type] = true;
        setTimeout(() => {
            this.isLoading[type] = false;
        }, 2000);
        const tempParams: any = {};
        Object.assign(tempParams, this.queryParams);
        if (!this.queryParams.vcFinished) {
            this.msg.error("请选择调整后作业日期！");
            return;
        }
        if (this.queryParams.vcFinished === '1' || this.queryParams.vcFinished === '2') {
            if (!this.infoParams.dtWorkdate) {
                this.msg.error("请选择调整后作业日期！");
                return;
            }
            if (!this.infoParams.vcDevid) {
                this.msg.error("请选择未完成设备！");
                return;
            }
        }
        tempParams.waName = '';
        tempParams.wsName = '';
        tempParams.staName = '';
        tempParams.dtSkywinplanetime = this.dateYearMonth(tempParams.dtSkywinplanetime);
        tempParams.dtSkywinplantime = this.dateYearMonth(tempParams.dtSkywinplantime);
        tempParams.dtWorkdate = this.datePipe.transform(tempParams.dtWorkdate, 'yyyy-MM-dd');
        tempParams.vcTeammembername = tempParams.vcTeammembername ? tempParams.vcTeammembername.toString() : '';
        tempParams.vcToolsmaterial = tempParams.vcToolsmaterial ? tempParams.vcToolsmaterial.replace(/，/g, ',') : '';
        tempParams.vcWorkinfo = tempParams.vcWorkinfo ? tempParams.vcWorkinfo.replace(/，/g, ',') : '';
        tempParams.vcIndoornum = tempParams.vcIndoornum ? tempParams.vcIndoornum : '';
        tempParams.vcOutdoornum = tempParams.vcOutdoornum ? tempParams.vcOutdoornum : '';
        tempParams.dtIndoortime = this.dateYearMonth(tempParams.dtIndoortime);
        tempParams.dtOutdoortime = this.dateYearMonth(tempParams.dtOutdoortime);
        tempParams.vcBlockadeTime = this.dateYearMonth(tempParams.vcBlockadeTime);
        tempParams.vcDispatchId = tempParams.vcDispatchId ? tempParams.vcDispatchId : '';
        tempParams.vcImpWorkId = tempParams.vcImpWorkId ? tempParams.vcImpWorkId : '';
        tempParams.vcMoreWorkId = tempParams.vcMoreWorkId ? tempParams.vcMoreWorkId : '';
        tempParams.vcOtherWorkId = tempParams.vcOtherWorkId ? tempParams.vcOtherWorkId : '';
        tempParams.vcYearPlanId = tempParams.vcYearPlanId ? tempParams.vcYearPlanId : '';

        tempParams.vcDealprobId = [];
        if (this.problemList) {
            for (const item of this.problemList) {
                if (item.checked) {
                    tempParams.vcDealprobId.push(item.id);
                }
            }
        }
        tempParams.vcDealprobId = tempParams.vcDealprobId ? tempParams.vcDealprobId.toString() : '';

        if (tempParams.sedate === 'null ~ null') {
            tempParams.sedate = "";
        }
        if (type === 'feedBack' && (this.finishStatus === '1' || this.finishStatus === '2')) {
            const params: any = {};
            Object.assign(params, tempParams);
            console.log("params");
            console.log(params);
            params.vcDevname = [];
            params.infoParams = this.infoParams.params;
            params.dtWorkdate = this.datePipe.transform(this.infoParams.dtWorkdate, 'yyyy-MM-dd');
            if (this.infoParams.vcDevid) {
                for (const item of this.devList) {
                    for (const list of this.infoParams.vcDevid) {
                        if (item.opValue === list) {
                            params.vcDevname.push(item.opName);
                        }
                    }
                }
                params.vcDevname = params.vcDevname.toString();
                params.vcDevid = this.infoParams.vcDevid.toString();
            }
            params.vcStatus = '6';

            let url = '';
            const oldData = this.queryParams.dtWorkdate + "";
            const newData = this.dateYearMonth(this.infoParams.dtWorkdate) + "";
            // 调整日期和原日期在一个月内
            url = oldData.substr(0, 7) === newData.substr(0, 7) ? environment.project + '/ymTDispatchlist/add' : environment.project + '/ymTDispatchlist/addmonthplanbydispatch';
            this.http.post(url, params).subscribe((res: any) => {
                if (!res.code) {
                    this.router.navigate(['dispatchList/execution']);
                } else {
                    res.msg ? this.msg.error(res.msg) : this.msg.error('操作失败');
                }
            });
        }

        tempParams.vcUnFinishedDevId = [];
        tempParams.vcUnFinishedDevName = [];
        tempParams.vcFinishedDevId = [];
        tempParams.vcFinishedDevName = [];

        if (this.infoParams.vcDevid) {
            for (const item of this.devList) {
                for (const list of this.infoParams.vcDevid) {
                    if (item.opValue === list) {
                        tempParams.vcUnFinishedDevId.push(item.opValue);
                        tempParams.vcUnFinishedDevName.push(item.opName);
                    }
                }
            }
            this.queryParams.vcDevid.split(',').forEach(v => {
                if (tempParams.vcUnFinishedDevId.indexOf(v) === -1) {
                    tempParams.vcFinishedDevId.push(v)
                }
            });
            this.queryParams.vcDevname.split(',').forEach(v => {
                if (tempParams.vcUnFinishedDevName.indexOf(v) === -1) {
                    tempParams.vcFinishedDevName.push(v)
                }
            });
        }
        else {
            tempParams.vcFinishedDevId = this.queryParams.vcDevid;
            tempParams.vcFinishedDevName = this.queryParams.vcDevname;
        }
        tempParams.vcUnFinishedDevId = tempParams.vcUnFinishedDevId ? tempParams.vcUnFinishedDevId.toString() : '';
        tempParams.vcUnFinishedDevName = tempParams.vcUnFinishedDevName ? tempParams.vcUnFinishedDevName.toString() : '';
        tempParams.vcFinishedDevId = tempParams.vcFinishedDevId ? tempParams.vcFinishedDevId.toString() : '';
        tempParams.vcFinishedDevName = tempParams.vcFinishedDevName ? tempParams.vcFinishedDevName.toString() : '';
        tempParams.vcStatus = type === 'feedBack' ? '6' : '4';

        this.http.post(environment.project + '/ymTDispatchlist/update', tempParams).subscribe((res: any) => {
            if (!res.code) {
                this.router.navigate(['dispatchList/execution']);
            } else {
                res.msg ? this.msg.error(res.msg) : this.msg.error('操作失败');
            }
        });
    }
}
